package com.spshiro.controller;

import com.spshiro.service.imp.UserServiceimp;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * @create 2022-03-2022/3/16-21:03
 */
@Controller
public class HelloController {

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello,shiro");
        return "index";
    }

    @RequestMapping("/user/addUser")
    public String addUser( ){

        return "user/addUser";
    }

    @RequestMapping("/user/updateUser")
    public String updateUser( ){

        return "user/updateUser";
    }

    @RequestMapping("/toLogin")
    public String toLogin(Model  model){
        //model.addAttribute("msg","没权限请登录");
        return "login";
    }


   // public String caoZuo(){
      //  return "redirect:/index";
   // }


    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前用户
        Subject subject= SecurityUtils.getSubject();
        //封装用户登录数据
        UsernamePasswordToken token =new UsernamePasswordToken(username,password);
        token.setRememberMe(true);

        try {
            //验证并执行登录
            subject.login(token);
            model.addAttribute("msgyz ","1");
            return  "index";
        }catch (UnknownAccountException e ){//用户名不存在
            model.addAttribute("msg","账户不存在");
            return "login";
        }catch (IncorrectCredentialsException e) {//密码错误
            model.addAttribute("msg", "密码错误");
            return "login";
        }

    }


    @RequestMapping("/unauthentic")
    //@ResponseBody
    public String unauthc(){
        return "unauthentic";
       // return "未授权无法访问";
    }
}
